<?php
/**
 * Created by PhpStorm.
 * User: My
 * Date: 2018/2/25
 * Time: 15:09
 */

namespace RjgcPay\AliPagePay;

use RjgcPay\AliPagePay\buildermodel\AlipayTradeCloseContentBuilder;
use RjgcPay\AliPagePay\buildermodel\AlipayTradeFastpayRefundQueryContentBuilder;
use RjgcPay\AliPagePay\buildermodel\AlipayTradePagePayContentBuilder;
use RjgcPay\AliPagePay\buildermodel\AlipayTradeQueryContentBuilder;
use RjgcPay\AliPagePay\buildermodel\AlipayTradeRefundContentBuilder;

use RjgcPay\PayModeInterface;

require_once dirname(dirname ( __FILE__ )).'/lib/ali_sdk/AopSdk.php';

/**
 * 支付宝支付处理类-PC网站支付
 *
 * @package RjgcPay\AliPagePay
 */
class PayMode implements PayModeInterface
{
    private $pay;
    private $is_debug=false;
    private $is_page=false;

    /**
     * 支付构造函数
     * PayMode constructor.
     * @param $app_config  自定义配置信息(外部)
     * @param $payMode_config  特定支付配置信息（内部）
     * @throws \Exception
     */
    public function __construct($app_config,$payMode_config)
    {
        if (!empty($app_config)){
            $pay=new Pay($app_config);
            $this->is_debug=isset($app_config['is_debug'])?$app_config['is_debug']:false;

        }
        elseif (!empty($payMode_config)){
            $pay=new Pay($payMode_config);
            $this->is_debug=isset($payMode_config['is_debug'])?$payMode_config['is_debug']:false;
        }
        else{
            throw new \Exception('未定义应用端类型','444');
        }

        $this->pay=$pay;
    }

    /**
     * 统一付款接口
     *
     * @param $data  支付需要提供的参数
     * @return bool|mixed|\SimpleXMLElement|string|\提交表单HTML文本
     */
    public function unifiedPay($data)
    {

        //构造支付订单参数
        $payRequestBuilder=new AlipayTradePagePayContentBuilder();
        $payRequestBuilder->setBody($data['body']);
        $payRequestBuilder->setSubject($data['subject']);
        $payRequestBuilder->setTotalAmount($data['total_amount']);
        $payRequestBuilder->setOutTradeNo($data['out_trade_no']);

        $biz_content=$payRequestBuilder->getBizContent();


        //支付订单参数
        $request=new \AlipayTradePagePayRequest();
        $request->setReturnUrl($this->pay->getReturnUrl());
        $request->setNotifyUrl($this->pay->getNotifyUrl());
        $request->setBizContent ($biz_content);

        //执行操作
        $result=$this->_execute($request);
        return $result;

    }


    /**
     * 统一同步通知回调处理.
     *
     * @param \RjgcPay\支付后支付平台同步返回的数据 $data
     * @return bool|mixed
     */
    public function unifiedReturnUrl($data)
    {
        $this->writeLog(json_encode($data,JSON_UNESCAPED_UNICODE));
        return $this->check($data);
    }

    /**
     * 统一异步通知回调处理.
     *
     * @param \RjgcPay\支付后支付平台异步返回的数据 $data
     * @return bool|mixed
     */
    public function unifiedReturnNotify($data)
    {
        $this->writeLog(json_encode($data,JSON_UNESCAPED_UNICODE));
        return $this->check($data);
    }

    /**
     * 统一收单线下交易查询.
     *
     * @param \RjgcPay\查询条件项 $data
     * @return bool|\SimpleXMLElement[]|string|\提交表单HTML文本\
     */
    public function unifiedQuery($data)
    {
        //构造查询订单参数
        $requestBuilder=new AlipayTradeQueryContentBuilder($data);

        $biz_content=$requestBuilder->getBizContent();

        //查询订单参数
        $request=new \AlipayTradeQueryRequest();
        $request->setBizContent($biz_content);

        //执行操作
        $response=$this->_execute($request);
        $response = $response->alipay_trade_query_response;
        return $response;



    }


    /**
     * 统一收单交易关闭接口.
     *
     * @param \RjgcPay\关闭条件项 $data
     * @return bool|\SimpleXMLElement[]|string|\提交表单HTML文本
     */
    public function unifiedClose($data)
    {
        $requestBuilder=new AlipayTradeCloseContentBuilder($data);

        $biz_content=$requestBuilder->getBizContent();

        $request=new \AlipayTradeCloseRequest();
        $request->setBizContent ( $biz_content );

        //执行操作
        $response=$this->_execute($request);
        $response = $response->alipay_trade_query_response;
        return $response;


    }

    /**
     * 统一收单交易退款接口.
     *
     * @param \RjgcPay\退款参数 $data
     * @return bool|\SimpleXMLElement[]|string|\提交表单HTML文本
     */
    public function unifiedRefund($data)
    {
        $requestBuilder=new AlipayTradeRefundContentBuilder($data);

        $biz_content=$requestBuilder->getBizContent();

        $request=new \AlipayTradeRefundRequest();
        $request->setBizContent ( $biz_content );

        //执行操作
        $response=$this->_execute($request);
        $response = $response->alipay_trade_refund_response;
        return $response;

    }


    /**
     * 统一收单交易退款查询.
     *
     * @param \RjgcPay\退款查询条件 $data
     * @return bool|mixed|\SimpleXMLElement|string|\提交表单HTML文本
     */
    public function unifiedRefundQuery($data)
    {
        $requestBuilder=new AlipayTradeFastpayRefundQueryContentBuilder($data);

        $biz_content=$requestBuilder->getBizContent();

        $request=new \AlipayTradeFastpayRefundQueryRequest();
        $request->setBizContent ( $biz_content );

        //执行操作
        $response=$this->_execute($request);
        return $response;
    }


    public function unifiedDownloadurlQuery($data)
    {
        print_r('尚未实现');
        // TODO: Implement unifiedDownloadurlQuery() method.
    }

    /**
     * 验签方法
     *
     * @param $data 验签支付宝返回的信息，使用支付宝公钥
     */
    public function check($data)
    {
        $aop=new \AopClient();
        $aop->alipayrsaPublicKey=$this->pay->getAlipayPublicKey();

        $result=$aop->rsaCheckV1($data,$this->pay->getAlipayPublicKey(),$this->pay->getSigntype());

        return $result;
    }

    /**
     * 写入日志.
     *
     * @param $text
     */
    public function writeLog($text)
    {
        file_put_contents ( dirname ( __FILE__ ).DIRECTORY_SEPARATOR."./../../log.txt", date ( "Y-m-d H:i:s" ) . "  " . $text . "\r\n", FILE_APPEND );
    }


    private function _execute($request){
        $aop=new \AopClient();

        //公共参数
        $aop->gatewayUrl = $this->pay->getGatewayUrl();
        $aop->appId = $this->pay->getAppid();
        $aop->rsaPrivateKey = $this->pay->getPrivateKey();
        $aop->alipayrsaPublicKey=$this->pay->getAlipayPublicKey();
        $aop->apiVersion = $this->pay->getVersion();
        $aop->signType =$this->pay->getSigntype();
        $aop->postCharset=$this->pay->getCharset();
        $aop->format=$this->pay->getFormat();

        // 开启页面信息输出
        if ($this->is_debug){
            $aop->debugInfo=$this->is_debug;
        }

        //执行查询操作
        if ($this->is_page){
            //请求
            $result = $aop->pageExecute($request,"post");

            //输出
            echo $result;
        }
        else{
            $result = $aop->Execute($request);
        }

        return $result;
    }

}